package com.shuaiche.yeguan;

import android.app.Application;
import android.content.Context;
import android.text.TextUtils;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;
import com.facebook.react.defaults.DefaultReactNativeHost;
import com.facebook.soloader.SoLoader;
import com.shuaiche.ReactNativeFlipper;
import com.shuaiche.yeguan.config.SCAppConfig;
import com.shuaiche.yeguan.ui.login.OneLoginUtils;
import com.shuaiche.yeguan.model.SCMerchantDetailModel;
import com.shuaiche.yeguan.model.SCUserInfoResponse;
import com.shuaiche.yeguan.net.http.HttpHelper;
import com.shuaiche.yeguan.net.http.OkhttpRequest;
import com.shuaiche.yeguan.rn.AndroidPackage;
import com.shuaiche.yeguan.util.CrashHandler;
import com.shuaiche.yeguan.util.LogUtils;
import com.shuaiche.yeguan.util.SPUtils;
import com.shuaiche.yeguan.util.config.DataConfig;
import com.shuaiche.yeguan.util.config.PreferenceConfig;
import com.tencent.wework.api.IWWAPI;
import com.tencent.wework.api.WWAPIFactory;

import java.util.List;

import androidx.multidex.MultiDex;

public class SCApplication extends Application implements ReactApplication {

    public static SCApplication scApplication;
    private SCUserInfoResponse userinfoModel;

    /**
     * 企业信息
     */
    private SCMerchantDetailModel companyInfo;
    /**
     * 阿里oos客户端
     */
    private OSS ossClient;
    /**
     * 配置器
     */
    private DataConfig mCurrentConfig;

    public static String weworkAgentId = "";
    public static String weworkSchema = "";
    public static String weworkCorpId = "";
    public IWWAPI iwwapi;

    public static SCApplication getApplication() {
        return scApplication;
    }

  private final ReactNativeHost mReactNativeHost =
      new DefaultReactNativeHost(this) {
        @Override
        public boolean getUseDeveloperSupport() {
          return BuildConfig.DEBUG;
        }

        @Override
        protected List<ReactPackage> getPackages() {
          @SuppressWarnings("UnnecessaryLocalVariable")
          List<ReactPackage> packages = new PackageList(this).getPackages();
          // Packages that cannot be autolinked yet can be added manually here, for example:
           packages.add(new AndroidPackage());


          return packages;
        }

        @Override
        protected String getJSMainModuleName() {
          return "index";
        }

        @Override
        protected boolean isNewArchEnabled() {
          return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
        }

        @Override
        protected Boolean isHermesEnabled() {
          return BuildConfig.IS_HERMES_ENABLED;
        }
      };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    scApplication = this;
    SoLoader.init(this, /* native exopackage */ false);
    if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
      // If you opted-in for the New Architecture, we load the native entry point for this app.
      DefaultNewArchitectureEntryPoint.load();
    }

    ReactNativeFlipper.initializeFlipper(this, getReactNativeHost().getReactInstanceManager());

    int apiType = SPUtils.getInt(this,SPUtils.API_TYPE,0);
    boolean isDebug = BuildConfig.DEBUG;
    if (isDebug){
        HttpHelper.init(new OkhttpRequest(),apiType);
    }else {
        HttpHelper.init(new OkhttpRequest(),3);
    }

      boolean isAgree = SPUtils.getBoolean(this,SPUtils.IS_AGREE,false);
      if (isAgree){
          CrashHandler.getInstance().init(getApplicationContext());
          initSDKS();
          if (BuildConfig.DEBUG){
              LogUtils.setDebugMode();
          }
      }
  }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public void initSDKS() {
      initGeeTest();
      initWWX();
    }

    private void initGeeTest() {
        OneLoginUtils.init(this);
    }

    /**
     * 初始化企业微信
     */
    public void initWWX(){
        if (TextUtils.isEmpty(SCApplication.weworkSchema)){
            return;
        }
        iwwapi = WWAPIFactory.createWWAPI(this);
        iwwapi.registerApp(SCApplication.weworkSchema);
    }

    /***
     * 获取阿里云oss
     *
     * @return
     */
    public OSS getOssClient(String accessKeyId, String accessKeySecret, String securityToken) {
//        if (ossClient == null) {
        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
        OSSCredentialProvider credentialProvider =
                new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        if (SCAppConfig.IS_DEBUG) {
            OSSLog.enableLog();
        }
        ossClient = new OSSClient(getApplicationContext(), endpoint, credentialProvider, conf);
        return ossClient;
    }


    /***
     * 获取用户信息
     *
     * @return
     */
    public SCUserInfoResponse getUserinfoModel() {
        return userinfoModel;
    }

    /**
     * 设置用户信息
     */
    public void setUserinfoModel(SCUserInfoResponse userinfoModel) {
        this.userinfoModel = userinfoModel;
    }

    /***
     * 获取用户信息
     *
     * @return
     */
    public SCMerchantDetailModel getCompanyInfo() {
        return companyInfo;
    }

    /**
     * 设置用户信息
     */
    public void setCompanyInfoModel(SCMerchantDetailModel companyInfo) {
        this.companyInfo = companyInfo;
    }

    /**
     * 根据类型得到对应的配置器
     *
     * @return
     * @see [类、类#方法、类#成员]
     */
    public DataConfig getPreferenceConfig() {
        if (mCurrentConfig == null) {
            mCurrentConfig = PreferenceConfig.getPreferenceConfig(this);
            if (!mCurrentConfig.isLoadConfig()) {
                mCurrentConfig.loadConfig();
            }
        }
        return mCurrentConfig;
    }
}
